package com.cz.nongyetongv5.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.IconGrideAdapter;
import com.cz.nongyetongv5.adapter.ShouYeImageAdapter;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.JsonUtil;
import com.cz.nongyetongv5.bean.StayCheckBean;
import com.cz.nongyetongv5.bean.StayMarkBean;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.custom.viewflow.CircleFlowIndicator;
import com.cz.nongyetongv5.custom.viewflow.ViewFlow;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.DialogUtil;
import com.cz.nongyetongv5.utils.DownloadDataUtil;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;
import com.cz.nongyetongv5.utils.ImageUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class ShouYeActivity extends Fragment implements OnClickListener {
    private StayCheckBean stayCheckBean;
    private StayMarkBean stayMarkBean;
    /**
     * 待办数量
     */
    private int stayCount;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.shouye, null);
    }

    /**
     * 图标布局
     */
    private GridView gvIconLayout = null;

    /**
     * 主�D�丫值�Adapter
     */
    private BaseAdapter iconGridAdapter = null;

    /**
     * 主页的网格布局数据
     */
    private List<Map<String, Object>> iconGridData = null;

    // 用户的区域
    private User user = null;

    /**
     * 下载数据工具类
     */
    private DownloadDataUtil downloadDataUtil = null;

    /**
     * 验证的用户名
     */
    private String validateUsername = null;

    /**
     * 验证的密码
     */
    private String validatePassword = null;

    /**
     * 指示器的点
     */
    private CircleFlowIndicator viewflowindic = null;

    /**
     * 多个图片的布局
     */
    private ViewFlow viewFlow = null;

    private AsyncTask<Integer, Integer, Integer> taskNewsCount = null;

    /**
     * 上一次的新闻数量作为缓冲
     */
    private Integer preCount = null;

    private ConfigUtil configUtil = null;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        configUtil = new ConfigUtil(getResources());

        /**
         * 初始化验证的用户名和密码
         */
        validateUsername = new ConfigUtil(getResources()).getRestUsername();

        validatePassword = new ConfigUtil(getResources()).getRestPassword();

        /**
         * 初始化下载工具类
         */
        downloadDataUtil = DownloadDataUtil.getNewInstance();

        downloadDataUtil.setValidateUserName(validateUsername);

        downloadDataUtil.setValidatePassword(validatePassword);

        /**
         * 读取出town 的路径
         */
        user = (User) getActivity().getIntent().getExtras()
                .getSerializable("user");


        //        getStay(false);

        gvIconLayout = (GridView) getActivity().findViewById(R.id.gvIconLayout);

        // 填充�™
        iconGridData = new ArrayList<Map<String, Object>>();

        Map<String, Object> icon_xinwen = new HashMap<String, Object>();

        icon_xinwen.put("ibIconItem", R.drawable.xinwen_icon);
        icon_xinwen.put("tvIconItem", "新闻动态");

        if (preCount != null && preCount > 0) {

            icon_xinwen.put("count", preCount);

        }

        iconGridData.add(icon_xinwen);

        if (configUtil.jiandujiancha()) {

            Map<String, Object> icon_jianguan = new HashMap<String, Object>();
            icon_jianguan.put("ibIconItem", R.drawable.jianguan_icon);
            icon_jianguan.put("tvIconItem", "监督检查");
            iconGridData.add(icon_jianguan);
        }

        if (configUtil.duchaxuncha()) {
            Map<String, Object> icon_duchaxuncha = new HashMap<String, Object>();
            icon_duchaxuncha.put("ibIconItem", R.drawable.jianguan_icon);
            icon_duchaxuncha.put("tvIconItem", "督查巡查");
            iconGridData.add(icon_duchaxuncha);

        }

        Map<String, Object> icon_chanpinjiance = new HashMap<String, Object>();

        icon_chanpinjiance.put("ibIconItem", R.drawable.chanpinjiance_icon);
        icon_chanpinjiance.put("tvIconItem", "产品抽检");

        iconGridData.add(icon_chanpinjiance);

        Map<String, Object> icon_jianguanduixiang = new HashMap<String, Object>();

        icon_jianguanduixiang.put("ibIconItem",
                R.drawable.jianguanduixiang_icon);
        icon_jianguanduixiang.put("tvIconItem", "监管对象");

        iconGridData.add(icon_jianguanduixiang);


        Map<String, Object> icon_tongxun = new HashMap<String, Object>();

        icon_tongxun.put("ibIconItem", R.drawable.tongxun_icon);
        icon_tongxun.put("tvIconItem", "监管人员");

        iconGridData.add(icon_tongxun);


        if (configUtil.sanpinchaxun()) {

            Map<String, Object> icon_sanpin_chaxun = new HashMap<String, Object>();

            icon_sanpin_chaxun.put("ibIconItem", R.drawable.chaxun_icon);
            icon_sanpin_chaxun.put("tvIconItem", "三品查询");

            iconGridData.add(icon_sanpin_chaxun);
        }

        if (configUtil.tourupinchaxun()) {

            Map<String, Object> icon_touyongpin_chaxun = new HashMap<String, Object>();
            icon_touyongpin_chaxun.put("ibIconItem", R.drawable.chaxun_icon);
            icon_touyongpin_chaxun.put("tvIconItem", "投入品查询");

            iconGridData.add(icon_touyongpin_chaxun);

        }


        if (configUtil.hudongjiaoliu()) {
            Map<String, Object> icon_jiaoliu = new HashMap<String, Object>();

            icon_jiaoliu.put("ibIconItem", R.drawable.jiaoliu_icon);
            icon_jiaoliu.put("tvIconItem", "互动交流");

            iconGridData.add(icon_jiaoliu);
        }


        //消息提醒
        //        Map<String, Object> icon_jiaoliu = new HashMap<String, Object>();
        //
        //        icon_jiaoliu.put("ibIconItem", R.drawable.xinwen_icon);
        //        icon_jiaoliu.put("tvIconItem", "消息提醒");


        //        if (user.getKnowRegion().length() >= 8) {
        //            Map<String, Object> icon_stay = new HashMap<String, Object>();
        //            icon_stay.put("ibIconItem", R.drawable.chaxun_icon);
        //            icon_stay.put("tvIconItem", "待办事项");
        //            iconGridData.add(icon_stay);
        //            if (stayCount > 0) {
        //                icon_stay.put("count", stayCount);
        //            }
        //        }


        //        iconGridData.add(icon_jiaoliu);

        /**
         *协管汇总
         */
        Map<String, Object> icon_collect = new HashMap<String, Object>();
        icon_collect.put("ibIconItem", R.drawable.icon_collect);
        icon_collect.put("tvIconItem", "协管汇总");
        iconGridData.add(icon_collect);

        iconGridAdapter = new IconGrideAdapter(getActivity(),
                this.iconGridData, LayoutInflater.from(getActivity()
                .getBaseContext()), this);

        gvIconLayout.setAdapter(iconGridAdapter);

        List<Integer> imageDatas = new ArrayList<Integer>();

        Field[] fields = R.drawable.class.getDeclaredFields();

        for (Field field : fields) {
            if (field.getName().startsWith("function_expect")) {
                try {
                    imageDatas.add(field.getInt(null));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 初始化指示器的点
         */
        viewflowindic = (CircleFlowIndicator) this.getActivity().findViewById(
                R.id.viewflowindic);

        /**
         * 加载滑动的控件
         */
        viewFlow = (ViewFlow) this.getActivity().findViewById(R.id.viewflow);

        /**
         * 加载图片
         */
        List<Map<String, Bitmap>> imageUrlDatas = new ArrayList<Map<String, Bitmap>>();

        InitApplication application = (InitApplication) getActivity()
                .getApplicationContext();

        if (application.getMaxVersion() != null
                && application.getMaxVersion().getImageDatas().size() > 0) {

            imageUrlDatas = application.getMaxVersion().getImageDatas();
        } else {
            // 如果是不从网络读取的模式
            for (int i = 0; i < imageDatas.size(); i++) {

                int id = imageDatas.get(i);

                Map<String, Bitmap> imageMap = new HashMap<String, Bitmap>();

                imageMap.put("" + (i),
                        BitmapFactory.decodeResource(getResources(), id));

                imageUrlDatas.add(imageMap);

            }
        }

        /*
         * Map<String, Bitmap> imageMap = new HashMap<String, Bitmap>();
         *
         * imageMap.put("http://www.baidu.com/img/bdlogo.png", null);
         *
         * imageUrlDatas.add(imageMap);
         *
         *
         *
         * imageMap = new HashMap<String, Bitmap>();
         *
         * imageMap.put("http://www.baidu.com/img/bdlogo.png", null);
         *
         * imageUrlDatas.add(imageMap);
         *
         *
         *
         * imageMap = new HashMap<String, Bitmap>();
         *
         * imageMap.put("http://www.baidu.com/img/bdlogo.png", null);
         *
         * imageUrlDatas.add(imageMap);
         *
         * imageMap = new HashMap<String, Bitmap>();
         *
         * imageMap.put("http://www.baidu.com/img/bdlogo.png", null);
         *
         * imageUrlDatas.add(imageMap);
         */

        // 设置适配器
        viewFlow.setAdapter(new ShouYeImageAdapter(imageUrlDatas, getActivity()
                .getBaseContext()), 0);

        // 设置指示器的点
        viewFlow.setFlowIndicator(viewflowindic);

        viewFlow.setmSideBuffer(imageUrlDatas.size()); // 实际图片张数，
        // 我的ImageAdapter实际图片张数为3

        viewFlow.setTimeSpan(3500);

        viewFlow.startAutoFlowTimer(); // 启动自动播放

        refreshNewsCount();

        // new Thread() {
        //
        // public void run() {
        //
        // /*
        // * 聊天系统的初始化
        // */
        //
        // // 打开连接
        // XmppTool.getConnection();
        //
        // // 注册用户并且给
        // XmppTool.regUser(user.getUsername(),
        // CommonConstants.CHAT_USER_PASSWORD, null);
        //
        // };
        //
        // }.start();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        //
        //        if (requestCode == 1) {
        //
        //            refreshNewsCount();
        //
        //        }

    }

    // 按钮点击的时候的事件
    @Override
    public void onClick(View v) {
        RelativeLayout iconLayout = (RelativeLayout) v.getParent();
        // 主页图标点击的时候
        if (gvIconLayout != null
                && gvIconLayout.getPositionForView(iconLayout) > -1) {

            // 娜萜餮Y面督е贫ńM件的position
            int position = gvIconLayout.getPositionForView(iconLayout);

            String title = (String) iconGridData.get(position)
                    .get("tvIconItem");

            if ("新闻动态".equals(title)) {

                Intent to_newslist_intent = new Intent(getActivity(),
                        NewsListActivity.class);

                to_newslist_intent.putExtra("user", this.user);
                if (CommonConstants.isNetworkConnected(getActivity())) {
                    startActivityForResult(to_newslist_intent, 1);
                } else {
                    DialogUtil.showMessageDialog(getString(R.string.error_no_network), null, ShouYeActivity.this.getActivity());
                }


            }

            if ("监督检查".equals(title)) {

                File appDataFile = ImageUtil.getThisAppDataFile();

                File jianDuJianChaDataFile = new File(appDataFile,
                        "jiandujiancha");

                if (!jianDuJianChaDataFile.exists()) {

                    jianDuJianChaDataFile.mkdirs();

                }

                File jianDuJianChaListDataFile = new File(
                        jianDuJianChaDataFile, "list");

                if (!jianDuJianChaListDataFile.exists()) {
                    jianDuJianChaListDataFile.mkdirs();
                }

                if (CommonConstants.isNetworkConnected(getActivity())) {

                    // 传递到通讯录页面
                    Intent to_tongxunlu_intent = new Intent(getActivity(),
                            JianDuJianChaStatisticsActivity.class);

                    // 传递到下一个页面
                    to_tongxunlu_intent.putExtra("user", this.user);

                    startActivity(to_tongxunlu_intent);

                } else {
                    Intent to_jiandujiancha_intent = new Intent(getActivity(),
                            JianDuJianChaMainActivity.class);

                    // 传递到下一个页面
                    to_jiandujiancha_intent.putExtra("user", this.user);

                    startActivity(to_jiandujiancha_intent);
                    Toast.makeText(getActivity(), "未检测到网络,略过展示统计信息...",
                            Toast.LENGTH_LONG).show();

                }
            }

            if ("督查巡查".equals(title)) {

                File appDataFile = ImageUtil.getThisAppDataFile();

                File duChaXunChaDataFile = new File(appDataFile, "duchaxuncha");

                if (!duChaXunChaDataFile.exists()) {

                    duChaXunChaDataFile.mkdirs();

                }

                File duChaXunChaListDataFile = new File(duChaXunChaDataFile,
                        "list");

                if (!duChaXunChaListDataFile.exists()) {
                    duChaXunChaListDataFile.mkdirs();
                }

                if (CommonConstants.isNetworkConnected(getActivity())) {

                    // 传递到通讯录页面
                    Intent to_tongxunlu_intent = new Intent(getActivity(),
                            DuChaXunChaStatisticsActivity.class);

                    // 传递到下一个页面
                    to_tongxunlu_intent.putExtra("user", this.user);

                    startActivity(to_tongxunlu_intent);

                } else {
                    Intent to_jiandujiancha_intent = new Intent(getActivity(),
                            DuChaXunChaMainActivity.class);

                    // 传递到下一个页面
                    to_jiandujiancha_intent.putExtra("user", this.user);

                    startActivity(to_jiandujiancha_intent);
                    Toast.makeText(getActivity(), "未检测到网络,略过展示统计信息...",
                            Toast.LENGTH_LONG).show();

                }
            }

            // 产品检测
            if ("产品抽检".equals(title)) {
                File appDataFile = ImageUtil.getThisAppDataFile();

                File chanPinJianCeDataFile = new File(appDataFile,
                        "chanpinjiance");

                if (!chanPinJianCeDataFile.exists()) {

                    chanPinJianCeDataFile.mkdirs();

                }

                File chanPinJianCeListDataFile = new File(
                        chanPinJianCeDataFile, "list");

                if (!chanPinJianCeListDataFile.exists()) {
                    chanPinJianCeListDataFile.mkdirs();
                }

                //				// 传递到通讯录页面
                Intent to_tongxunlu_intent = new Intent(getActivity(),
                        ChanpinMenuActivity.class);

                // 传递到下一个页面
                to_tongxunlu_intent.putExtra("user", this.user);

                startActivity(to_tongxunlu_intent);

                //                startActivity(new Intent(getActivity(), activity_chouyang.class));
            }

            if ("监管对象".equals(title)) {

                if (CommonConstants.isNetworkConnected(getActivity())) {

                    // 传递到通讯录页面
                    Intent to_tongxunlu_intent = new Intent(getActivity(),
                            JianGuanDuiXiangStatisticsActivity.class);

                    // 传递到下一个页面
                    to_tongxunlu_intent.putExtra("user", this.user);

                    startActivity(to_tongxunlu_intent);

                } else {
                    Intent to_jianguanduixiang_intent = new Intent(
                            getActivity(), JianGuanDuiXiangActivity.class);

                    // 传递到下一个页面
                    to_jianguanduixiang_intent.putExtra("user", this.user);

                    startActivity(to_jianguanduixiang_intent);
                    Toast.makeText(getActivity(), "未检测到网络,略过展示统计信息...",
                            Toast.LENGTH_LONG).show();

                }

            }

            if ("三品查询".equals(title)) {
                Intent to_sanpin_chaxun_intent = new Intent(getActivity(),
                        SanPinChaXunActivity.class);

                to_sanpin_chaxun_intent.putExtra("user", this.user);

                startActivity(to_sanpin_chaxun_intent);

            }

            if ("投入品查询".equals(title)) {

                Intent to_tourupin_menu = new Intent(getActivity(),
                        TouRuPinMenuActivity.class);

                to_tourupin_menu.putExtra("user", this.user);

                startActivity(to_tourupin_menu);

            }

            if ("监管人员".equals(title)) {

                if (CommonConstants.isNetworkConnected(getActivity())) {

                    // 传递到通讯录页面
                    Intent to_tongxunlu_intent = new Intent(getActivity(),
                            TongXunLuStatisticsActivity.class);

                    // 传递到下一个页面
                    to_tongxunlu_intent.putExtra("user", this.user);

                    startActivity(to_tongxunlu_intent);

                } else {

                    Intent to_tongxunlu_intent = new Intent(getActivity(),
                            TongXunLuActivity.class);

                    // 传递到下一个页面
                    to_tongxunlu_intent.putExtra("user", this.user);

                    startActivity(to_tongxunlu_intent);
                    Toast.makeText(getActivity(), "未检测到网络,略过展示统计信息...",
                            Toast.LENGTH_LONG).show();

                }

            }

            if ("互动交流".equals(title)) {

                DialogUtil.showMessageDialog("互动交流正在开发..敬请期待..", null,
                        getActivity());
            }
            if ("消息提醒".equals(title)) {
                if (CommonConstants.isNetworkConnected(getActivity())) {
                    Intent to_tongxunlu_intent = new Intent(getActivity(),
                            MessageActivity.class);
                    to_tongxunlu_intent.putExtra("user", this.user);
                    startActivity(to_tongxunlu_intent);

                } else {
                    Toast.makeText(getActivity(), "未检测到网络,无法获取消息...",
                            Toast.LENGTH_LONG).show();
                }

            }


            if ("待办事项".equals(title)) {
                if (stayCount == 0) {
                    Toast.makeText(getActivity(), "暂无待办事项...",
                            Toast.LENGTH_LONG).show();
                } else {
                    Intent intent = new Intent(getActivity(), StayNewActivity.class);
                    intent.putExtra("stayCheck", stayCheckBean.getData());
                    intent.putExtra("user", user);
                    startActivity(intent);
                }
                //                Toast.makeText(getActivity(), "待办事项...",
                //                        Toast.LENGTH_LONG).show();
            }

            if ("协管汇总".equals(title)) {
                Intent intent = new Intent(getActivity(), AssistCollectActivity.class);
                intent.putExtra("user", user);
                startActivity(intent);
                //                Toast.makeText(getActivity(), "待办事项...",
                //                        Toast.LENGTH_LONG).show();
            }

        }

    }

    /**
     * 获取待办
     */
    void getStay(final boolean isShow) {
        OkHttpUtils
                .get()
                .url(InitApplication.newUrl + "system/getCheckMatter.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("region_code", user.getKnowRegion())
                .addParams("realname", user.getRealname())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        getMark();
                        //                        Toast.makeText(getActivity(), "请求失败，稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //                        System.out.println(response);
                        stayCheckBean = JsonUtil.toObject(response, StayCheckBean.class);

                        //                        if (stayCheckBean != null) {
                        //                            if (stayCheckBean.getCode().equals("0")) {
                        //                                if (!iconGridData.get(5).get("tvIconItem").equals("待办事项")) {
                        //                                    Map<String, Object> icon_stay = new HashMap<String, Object>();
                        //                                    icon_stay.put("ibIconItem", R.drawable.icon_daiban);
                        //                                    icon_stay.put("tvIconItem", "待办事项");
                        //                                    stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                        //                                            stayCheckBean.getData().getSuperviseCount();
                        //                                    if (stayCount > 0) {
                        //                                        icon_stay.put("count", stayCount);
                        //                                    }
                        //                                    iconGridData.add(5, icon_stay);
                        //                                    iconGridAdapter.notifyDataSetChanged();
                        //                                } else {
                        //                                    stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                        //                                            stayCheckBean.getData().getSuperviseCount();
                        //                                    iconGridData.get(5).put("count", stayCount);
                        //                                    iconGridAdapter.notifyDataSetChanged();
                        //                                }
                        //                            } else {
                        //                                Toast.makeText(getActivity(), stayCheckBean.getMesssage(), Toast.LENGTH_SHORT).show();
                        //                            }
                        //                    }
                        getMark();
                    }
                });
    }


    void getMark() {
        OkHttpUtils
                .get()
                .url(InitApplication.markUrl + "system/getMarkMatter.json")
                .addParams("addFrom", "1")
                .addParams("addMark", "android")
                .addParams("region_code", user.getKnowRegion())
                .addParams("realname", user.getRealname())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (!iconGridData.get(5).get("tvIconItem").equals("待办事项")) {
                            Map<String, Object> icon_stay = new HashMap<String, Object>();
                            icon_stay.put("ibIconItem", R.drawable.icon_daiban);
                            icon_stay.put("tvIconItem", "待办事项");
                            if (stayCheckBean != null) {
                                stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                                        stayCheckBean.getData().getSuperviseCount();
                            }
                            if (stayCount > 0) {
                                icon_stay.put("count", stayCount);
                            }
                            iconGridData.add(5, icon_stay);
                            iconGridAdapter.notifyDataSetChanged();
                        } else {
                            if (stayCheckBean != null ) {
                                stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                                        stayCheckBean.getData().getSuperviseCount();
                            }
                            iconGridData.get(5).put("count", stayCount);
                            iconGridAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response);
                        stayMarkBean = JsonUtil.toObject(response, StayMarkBean.class);
                        //                        stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                        //                                stayCheckBean.getData().getSuperviseCount() + stayMarkBean.getData().getUserCount() +
                        //                                stayMarkBean.getData().getRegisterCount() + stayMarkBean.getData().getEntCount();
                        //                        iconGridData.get(5).put("count", stayCount);
                        //                        iconGridAdapter.notifyDataSetChanged();
                        if (stayMarkBean.getCode().equals("0")) {
                            if (!iconGridData.get(5).get("tvIconItem").equals("待办事项")) {
                                Map<String, Object> icon_stay = new HashMap<String, Object>();
                                icon_stay.put("ibIconItem", R.drawable.icon_daiban);
                                icon_stay.put("tvIconItem", "待办事项");
                                if (stayCheckBean != null && stayCheckBean.getData() != null) {
                                    stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                                            stayCheckBean.getData().getSuperviseCount() + stayMarkBean.getData().getUserCount() +
                                            stayMarkBean.getData().getRegisterCount() + stayMarkBean.getData().getEntCount();
                                } else {
                                    stayCount = stayMarkBean.getData().getUserCount() +
                                            stayMarkBean.getData().getRegisterCount() + stayMarkBean.getData().getEntCount();
                                }
                                //                                stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                                //                                stayCheckBean.getData().getSuperviseCount();
                                if (stayCount > 0) {
                                    icon_stay.put("count", stayCount);
                                }
                                iconGridData.add(5, icon_stay);
                                iconGridAdapter.notifyDataSetChanged();
                            } else {
                                if (stayCheckBean != null && stayCheckBean.getData() != null) {
                                    stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                                            stayCheckBean.getData().getSuperviseCount() + stayMarkBean.getData().getUserCount() +
                                            stayMarkBean.getData().getRegisterCount() + stayMarkBean.getData().getEntCount();
                                } else {
                                    stayCount = stayMarkBean.getData().getUserCount() +
                                            stayMarkBean.getData().getRegisterCount() + stayMarkBean.getData().getEntCount();
                                }
                                iconGridData.get(5).put("count", stayCount);
                                iconGridAdapter.notifyDataSetChanged();
                            }
                        } else {
                            if (!iconGridData.get(5).get("tvIconItem").equals("待办事项")) {
                                Map<String, Object> icon_stay = new HashMap<String, Object>();
                                icon_stay.put("ibIconItem", R.drawable.icon_daiban);
                                icon_stay.put("tvIconItem", "待办事项");
                                if (stayCheckBean != null) {
                                    stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                                            stayCheckBean.getData().getSuperviseCount();
                                }
                                if (stayCount > 0) {
                                    icon_stay.put("count", stayCount);
                                }
                                iconGridData.add(5, icon_stay);
                                iconGridAdapter.notifyDataSetChanged();
                            } else {
                                if (stayCheckBean != null ) {
                                    stayCount = stayCheckBean.getData().getCheckCount() + stayCheckBean.getData().getEntCount() +
                                            stayCheckBean.getData().getSuperviseCount();
                                }
                                iconGridData.get(5).put("count", stayCount);
                                iconGridAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
    }


    public void refreshNewsCount() {
        if (taskNewsCount == null || taskNewsCount.isCancelled()) {

            taskNewsCount = new AsyncTask<Integer, Integer, Integer>() {

                private int responseCodeRet;

                private String responseTxtRet;

                @Override
                protected Integer doInBackground(Integer... params) {

                    HttpUtils httpUtils = HttpUtils.getInstance();

                    httpUtils.setOnRequestExecuted(new OnRequestExecuted() {

                        @Override
                        public void onRequestExecuted(int responseCode,
                                                      String responseBody) {

                            responseCodeRet = responseCode;

                            responseTxtRet = responseBody;
                        }
                    });

                    String requestUrl = new ConfigUtil(getResources())
                            .getPreHttpUrl()
                            + getResources().getString(R.string.new_count)
                            + user.getUsername();

                    String authUserName = new ConfigUtil(getResources())
                            .getRestUsername();
                    String authPassword = new ConfigUtil(getResources())
                            .getRestPassword();

                    httpUtils.sendRequest(requestUrl, null, "GET", "UTF-8",
                            authUserName, authPassword, user);

                    return null;
                }

                @Override
                protected void onPostExecute(Integer result) {

                    int count = 0;

                    if (responseCodeRet == 200) {

                        try {
                            JSONObject jsonObject = new JSONObject(
                                    responseTxtRet);

                            count = jsonObject.getInt("result");

                            preCount = count;

                        } catch (JSONException e) {
                        }

                    }
                    //                    System.out.println(iconGridData.get(0).get("count") + "" + iconGridData.get(0).get("tvIconItem"));
                    if (count > 0) {
                        iconGridData.get(0).put("count", count);
                        iconGridAdapter.notifyDataSetChanged();
                    } else {
                        if (preCount != null && preCount > 0) {
                            iconGridData.get(0).put("count", preCount);
                            iconGridAdapter.notifyDataSetChanged();
                        }

                    }
                    //                    System.out.println(iconGridData.get(7).get("count")+"" + iconGridData.get(7).get("tvIconItem"));
                    this.cancel(true);
                }

            }.execute();

        }
    }


    @Override
    public void onResume() {
        super.onResume();
        refreshNewsCount();
        //        System.out.println(user.getKnowRegion());
        if (user.getKnowRegion().length() >= 8) {
            getStay(true);
        }
    }
}
